import { ObjType } from '@/@type/index'
import { Component, Vue } from 'vue-property-decorator'
import config from '@/config'
import { deep } from '@/utils'

const LIMIT = config.pageSizeKey
const PAGE = config.pageNumKey
const TOTAL = config.totalKey
const LIST = config.pageListKey

@Component
export default class extends Vue {
  total = 0
  pageInfo = {
    [LIMIT]: 10,
    [PAGE]: 1
  }
  _pageInfo = {}
  created() {
    this._pageInfo = deep(this.pageInfo)
  }
  resData = {} as ObjType
  listData = [] as any[] //列表数据
  listLoading = false // 滚动加载请求中
  listFinished = false //是否没有更多数据
  isLoading = false //下拉刷新
  canLoading = true

  //请求方法 (子方法复写)
  onloadList() {
    return Promise.reject() as Promise<any>
  }

  listLoad() {
    this.handleLoad()
  }

  handleLoad() {
    console.log('handleLoad', this.listLoading, this.listFinished)
    if (this.listLoading || this.listFinished) {
      //如果正在请求中/请求结束 取消请求
      return
    }
    this.listLoading = true
    this.onloadList()
      .then((res: any) => {
        console.log('接口请求完成开始处理数据:', res)
        this.resData = res
        this.total = res[TOTAL]
        const len = this.listData.length
        if (this.total <= len || (res[LIST] && res[LIST].length === 0)) {
          this.listFinished = true
          return
        }
        this.pageInfo[PAGE]++
      })
      .finally(() => {
        this.listLoading = false
        this.isLoading = false
        uni.stopPullDownRefresh()
      })
  }
  resetPageInfo() {
    this.pageInfo = deep(this._pageInfo)
  }

  listRefresh(isPullDown = false) {
    this.isLoading = isPullDown
    if (!isPullDown) {
      this.listData = []
    }
    this.listLoading = false
    this.listFinished = false
    this.resetPageInfo()
    console.log('listRefresh')
    this.listLoad()
  }

  //处理更新列表数据
  pageScrollTop = false
  handelEventListen(event, showApi) {
    console.log('handelEventListen')
    event.off()
    event.on(({ id }) => {
      if (id) {
        const index = this.listData.findIndex((i) => i.id === id)
        if (index !== -1) {
          showApi({ id }).then((res) => {
            this.listData.splice(index, 1, res)
          })
        }
      } else {
        this.listRefresh(true)
        this.pageScrollTop = true
      }
    })
  }

  onShow() {
    if (this.pageScrollTop) {
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 0
        })
        this.pageScrollTop = false
      })
    }
  }
  //可自己重写
  onReachBottom() {
    console.log('mixin onReachBottom')
    if (this.canLoading) {
      this.listLoad()
    }
  }
  onPullDownRefresh() {
    console.log('mixin onPullDownRefresh')
    this.listRefresh()
  }
}
